//
//  RECViewCell.m
//  CarFace
//
//  Created by dlios on 15/3/25.
//  Copyright (c) 2015年 蓝鸥科技. All rights reserved.
//

#import "RECViewCell.h"
#import "RECTableViewCell.h"
#import "NumTwolist.h"
#import "RECNumTwoTableViewCell.h"
#import "RECMediaTypeSixCell.h"




// 推出页面
#import "RECWebViewController.h"

@interface RECViewCell ()

@property(nonatomic, retain)NSMutableArray *listArr;
//十四个page
@property(nonatomic, assign)NSInteger page;

@property(nonatomic, retain)NSArray *listArr_num;

//@property(nonatomic, assign)BOOL isloadmore;
@end

@implementation RECViewCell
- (void)dealloc
{
//    Block_copy(_fastNewsblock);
    Block_release(_pushWebblock);
    Block_release(_photoViewblock);
    [_tableView release];
    [super dealloc];
}
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        

        self.tableView = [[UITableView alloc] init];
        self.tableView.delegate = self;
        self.tableView.dataSource = self;
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.contentView addSubview:self.tableView];
        [_tableView release];
        
        self.listArr = [NSMutableArray array];
        //应该建立14个重用池, 防止重用池的重用,造成数据刷新不完全
        [self.tableView registerClass:[RECTableViewCell class] forCellReuseIdentifier:@"tableOne"];
         [self.tableView registerClass:[RECNumTwoTableViewCell class] forCellReuseIdentifier:@"RECNumTwoCell"];
        [self.tableView registerClass:[RECMediaTypeSixCell class] forCellReuseIdentifier:@"tableTwo"];
        [self.tableView registerClass:[RECTableViewCell class] forCellReuseIdentifier:@"tableThree"];
        
        self.listArr_num = [NSArray arrayWithObjects:
                       @"http://app.api.autohome.com.cn/autov4.6/news/newslist-a2-pm2-v4.6.1-c0-nt0-p1-s20-l0.html",
                       @"http://app.api.autohome.com.cn/autov4.6/news/fastnewslist-a2-pm2-v4.6.1-b0-l0-s20-lastid0.html",
                       @"http://app.api.autohome.com.cn/autov4.6/news/videolist-a2-pm2-v4.6.1-vt0-s20-lastid0.html",
                       @"http://app.api.autohome.com.cn/autov4.6/news/newslist-a2-pm2-v4.6.1-c0-nt1-p1-s20-l0.html",
                       @"http://app.api.autohome.com.cn/autov4.6/news/newslist-a2-pm2-v4.6.1-c0-nt3-p1-s20-l0.html",
                       @"http://app.api.autohome.com.cn/autov4.6/news/newslist-a2-pm2-v4.6.1-c0-nt60-p1-s20-l0.html",
                       @"http://app.api.autohome.com.cn/autov4.6/news/newslist-a2-pm2-v4.6.1-c210200-nt2-p1-s20-l0.html",
                       @"http://app.api.autohome.com.cn/autov4.6/news/newslist-a2-pm2-v4.6.1-c0-nt82-p1-s20-l0.html",
                       @"http://app.api.autohome.com.cn/autov4.6/news/newslist-a2-pm2-v4.6.1-c0-nt102-p1-s20-l0.html",
                       @"http://app.api.autohome.com.cn/autov4.6/news/newslist-a2-pm2-v4.6.1-c0-nt97-p1-s20-l0.html",
                       @"http://app.api.autohome.com.cn/autov4.6/news/newslist-a2-pm2-v4.6.1-c0-nt107-p1-s20-l0.html",
                       @"http://app.api.autohome.com.cn/autov4.6/news/newslist-a2-pm2-v4.6.1-c0-nt100-p1-s20-l0.html",
                       @"http://app.api.autohome.com.cn/autov4.6/news/videolist-a2-pm2-v4.6.1-vt8-s20-lastid0.html",
                       @"http://app.api.autohome.com.cn/autov4.6/news/shuokelist-a2-pm2-v4.6.1-s20-lastid0.html",nil];

        _page = 2;
        
        [self.tableView addHeaderWithTarget:self action:@selector(addheader:)];
        [self.tableView addFooterWithTarget:self action:@selector(footfresh:)];
        [self.tableView setHeaderRefreshingText:@"刷新网络..."];
        [self.tableView setFooterRefreshingText:@"网络加载中..."];
    }
    return self;
}

// 进行数据刷新
- (void)addheader:(UITableView *)table
{
//    __unsafe_unretained typeof(self) vc = self;
    _page = 1;
    // 添加下拉刷新头部控件
    [self.tableView addHeaderWithCallback:^{
        // 进入刷新状态就会回调这个Block
        [self handleData];
        // 增加5条假数据
        
        // 模拟延迟加载数据，因此2秒后才调用（真实开发中，可以移除这段gcd代码）
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 结束刷新
//            [vc.tableView headerEndRefreshing];
//
//        });
    } dateKey:@"collection"];
    // dateKey用于存储刷新时间，也可以不传值，可以保证不同界面拥有不同的刷新时间
//      [self.tableView headerBeginRefreshing];

}

- (void)footfresh:(UITableView *)table
{
    __unsafe_unretained typeof(self) vc = self;
    // 添加上拉刷新尾部控件
    [self.tableView addFooterWithCallback:^{
       NSInteger  judge = [[_addDic objectForKey:@"num"] integerValue];
        NSInteger i = [[_addDic objectForKey:@"num"] integerValue];
        //页面等于0的时候刷新
        if (judge == 0) {
            NSString *str =[self.listArr_num[i] stringByReplacingOccurrencesOfString:@"p1" withString:[NSString stringWithFormat:@"p%ld", _page]];
            _page = _page + 1;
            [self handle:str];
        }else if(judge == 1 || judge == 2 || judge == 12 || judge == 13){
//            快报页面们
            NSString *str = [self.listArr_num[i] stringByReplacingOccurrencesOfString:@"lastid0" withString: [NSString stringWithFormat:@"lastid%@",[[self.listArr lastObject] lastid]]];
//            NSLog(@"-------------lastid%@", str);
            [self handle:str];
        }else{
            NSString *str = [self.listArr_num[i] stringByReplacingOccurrencesOfString:@"l0" withString: [NSString stringWithFormat:@"l%@",[[self.listArr lastObject] lasttime]]];
//            NSLog(@"_______str:%@", str);
            [self handle:str];
        }
        
//        [self.tableView reloadData];
 
        }];

        // 模拟延迟加载数据，因此2秒后才调用（真实开发中，可以移除这段gcd代码）
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            [vc.tableView reloadData];
            // 结束刷新
            [vc.tableView footerEndRefreshing];
        });
   
}

- (void)setAddDic:(NSDictionary *)addDic
{
    if (_addDic != addDic) {
        [_addDic release];
        _addDic = [addDic retain];
    }
//    [self handleData];

    [self.tableView headerBeginRefreshing];
    // 改变frame
    if ([[addDic objectForKey:@"num"] intValue] == 0) {
        self.tableView.frame = CGRectMake(0, self.contentView.frame.size.height / 4 + 70, self.contentView.frame.size.width, self.contentView.frame.size.height * 3 / 4 - 119);
    }
    if ([[addDic objectForKey:@"num"] intValue] >= 1) {
        self.tableView.frame = CGRectMake(0,  60, self.contentView.frame.size.width, self.contentView.frame.size.height - 119);
    }
}

- (void)handle:(NSString *)str
{
    NSInteger  judge = [[_addDic objectForKey:@"num"] intValue];
//     [self.listArr removeAllObjects];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSError *error = nil;
        NSJSONSerialization *result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error];
        //        判断为第 0 个collection的时候, 进行网络加载

        if (judge == 0 || judge == 3 || judge == 4 || judge == 5 || judge == 6 || judge == 7 || judge == 8 || judge == 9 || judge == 10 || judge == 11) {
            
            //        首页的newslist新闻
            NSMutableArray *newlistArr = [[result valueForKey:@"result"] objectForKey:@"newslist"];
//            self.isloadmore = [[result valueForKey:@"result"] objectForKey:@"isloadmore"];
//            NSLog(@"isloadmore: %d", _isloadmore);
            for (NSDictionary *newDic in newlistArr) {
                Newslist *newlist = [Newslist objectWithDictionary:newDic];
                [self.listArr addObject:newlist];
            }
        }
        // 快报页面
        else if (judge == 1){
            NSArray *resultArr = [[result valueForKey:@"result"] objectForKey:@"list"];
            //            NSLog(@"%ld", resultArr.count);
            //            [self.listArr removeAllObjects];
            for (NSDictionary *dic in resultArr) {
                NumTwolist *numTwo = [NumTwolist objectWithDictionary:dic];
                //                NSLog(@"%@", [numTwo title]);
                [self.listArr addObject:numTwo];
            }
            //            NSLog(@"%@", resultArr);
        }else if (judge == 2 || judge == 12 || judge == 13){
            NSMutableArray *newlistArr = [[result valueForKey:@"result"] objectForKey:@"list"];
            //            NSLog(@"-------%@",newlistArr);
            for (NSDictionary *newDic in newlistArr) {
                Newslist *newlist = [Newslist objectWithDictionary:newDic];
                //                NSLog(@"%@", [newlist title]);
                [self.listArr addObject:newlist];
            }
        }
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        });
        [_tableView reloadData];
        
    }
         failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             NSLog(@"%@", error);
         }];
}


- (void)handleData
{
    
    NSInteger  judge = [[_addDic objectForKey:@"num"] intValue];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager GET:[_addDic objectForKey:@"addStr"] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSError *error = nil;
        [self.listArr removeAllObjects];
        NSJSONSerialization *result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error];
        //        判断为第 0 个collection的时候, 进行网络加载
        if (judge == 0 || judge == 3 || judge == 4 || judge == 5 || judge == 6 || judge == 7 || judge == 8 || judge == 9 || judge == 10 || judge == 11) {
            //        [self.listArr removeAllObjects];
            //        首页的newslist新闻
            NSMutableArray *newlistArr = [[result valueForKey:@"result"] objectForKey:@"newslist"];
            for (NSDictionary *newDic in newlistArr) {
                Newslist *newlist = [Newslist objectWithDictionary:newDic];
                [self.listArr addObject:newlist];
            }
        }
        // 快报页面
        else if (judge == 1){
            NSArray *resultArr = [[result valueForKey:@"result"] objectForKey:@"list"];
            for (NSDictionary *dic in resultArr) {
                NumTwolist *numTwo = [NumTwolist objectWithDictionary:dic];
                [self.listArr addObject:numTwo];
            }
        }else if (judge == 2 || judge == 12 || judge == 13){
            NSMutableArray *newlistArr = [[result valueForKey:@"result"] objectForKey:@"list"];
            for (NSDictionary *newDic in newlistArr) {
                Newslist *newlist = [Newslist objectWithDictionary:newDic];
                [self.listArr addObject:newlist];
            }
        }
        
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        });
        [_tableView reloadData];
        [_tableView headerEndRefreshing];
    }
         failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             NSLog(@"%@", error);
             
         }];

}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
        return self.listArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
 
    // 判断是否是新闻第一页面
    if([self.listArr[indexPath.row] isKindOfClass:[NumTwolist class]]) {
        RECNumTwoTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"RECNumTwoCell"];
        cell.numTwolist = self.listArr[indexPath.row];
        return cell;
    }
    if ([[_addDic objectForKey:@"num"] integerValue] == 0) {
        if ([[self.listArr[indexPath.row] mediatype] intValue] == 6) {
            RECMediaTypeSixCell *cell = [tableView dequeueReusableCellWithIdentifier:@"tableTwo"];
            cell.newlist = self.listArr[indexPath.row];
            return cell;
        }
        RECTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"tableOne"];
        cell.newlist = self.listArr[indexPath.row];
        return cell;
        
    }
    RECTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"tableThree"];
    if ([[_addDic objectForKey:@"num"] integerValue] >= 2) {
        cell.newlist = self.listArr[indexPath.row];
    }
    return cell;

}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 设置第一界面的样式大小
    if ([[_addDic objectForKey:@"num"] integerValue] == 0) {
        if ([[self.listArr[indexPath.row] mediatype] intValue] == 6) {
            return self.contentView.frame.size.height / 6;
        }
    }
    if ([[self.addDic objectForKey:@"num"] intValue] == 1) {
        return self.contentView.frame.size.height / 3;
    }else{
        return self.contentView.frame.size.height / 8;
    }
    return 0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //第几个collection
    NSInteger num_page = [[_addDic objectForKey:@"num"] integerValue];
    NSString *str;
    
    NSString *str1 = [NSString stringWithFormat:@"%ld", [[self.listArr[indexPath.row] idStr] integerValue]];
    //在首页里判断.
    if (num_page == 0) {
        NSInteger judge =  [[self.listArr[indexPath.row] mediatype] intValue];
        NSString *str;
        
        if (judge == 6) {
            NSArray *line = [[self.listArr[indexPath.row] indexdetail] componentsSeparatedByString:@"㊣"];
            if (line.count == 0) {
                return;
            }
            
            NSString *ssStr = [line firstObject];
            NSString *spStr = [line objectAtIndex:1];
            str =[NSString stringWithFormat:@"http://app.api.autohome.com.cn/autov4.6/cars/cardutu-a2-pm2-v4.6.1-ss%@-sp%@-imgid%@-p1-s60-cid0-t0.html",ssStr, spStr, str1];
            _photoViewblock(str);
            return ;
        }

        if (judge == 1)
        {

            str = [NSString stringWithFormat:@"http://cont.app.autohome.com.cn/autov4.6/content/news/newscontent-n%@-t0.json", str1];
        }
        else if (judge == 2)
        {

            str =[NSString stringWithFormat:@"http://cont.app.autohome.com.cn/autov4.6/content/news/shuokecontent-a2-pm2-v4.6.1-n%@-nt0-lz0-p1-fs0-cw360.json", str1];
        }
        else if (judge == 3)
        {

            str =[NSString stringWithFormat:@"http://cont.app.autohome.com.cn/autov4.6/content/news/videopage-a2-pm2-v4.6.1-vid%@-night0-showpage1-fs0-cw1080.json", str1];
        }
        
        else if (judge == 5)
        {

            str = [NSString stringWithFormat:@"http://forum.app.autohome.com.cn/autov4.6/forum/club/topiccontent-a2-pm2-v4.6.0-t%@-o0-p1-s20-c1-nt0-fs0-sp0-al0-cw360.json", str1];
        }
//        else if(judge == 4){
        //   else if ([self.data.mediatype intValue] == 4) {
        //       str = [NSString stringWithFormat:@"http://forum.app.autohome.com.cn/autov4.6/forum/club/topiccontent-a2-pm2-v4.6.0-t39538716-o0-p1-s20-c1-nt0-fs0-sp0-al0-cw360.json", self.data.idStr];
        
//           }
        else if(judge == 7){
            str = [NSString stringWithFormat:@"http://cont.app.autohome.com.cn/autov4.6/content/News/fastnewscontent-n%@-lastid0.json", str1];
            if (self.delegate && [self.delegate respondsToSelector:@selector(pushPage:)]) {
                [self.delegate pushPage:str];
            }
        }else{

            str = [NSString stringWithFormat:@"http://cont.app.autohome.com.cn/autov4.6/content/news/newscontent-n%@-t0.json", str1];
        }
        self.pushWebblock(str, judge);
    }else if (num_page == 2 || num_page == 12) {
        str =[NSString stringWithFormat:@"http://cont.app.autohome.com.cn/autov4.6/content/news/videopage-a2-pm2-v4.6.1-vid%@-night0-showpage1-fs0-cw1080.json", str1];
        self.pushWebblock(str, 0);
    }else if (num_page == 13){
        str =[NSString stringWithFormat:@"http://cont.app.autohome.com.cn/autov4.6/content/news/shuokecontent-a2-pm2-v4.6.1-n%@-nt0-lz0-p1-fs0-cw360.json", str1];
        self.pushWebblock(str, 0);
    }else if(num_page == 4){
        str = [NSString stringWithFormat:@"http://cont.app.autohome.com.cn/autov4.6/content/news/newscontent-n%@-t0.json", str1];
        self.pushWebblock(str, 0);
    }else if (num_page == 6){
        NSLog(@"%@", str1);
//        str = [NSString stringWithFormat:@"http://forum.app.autohome.com.cn/autov4.6/forum/club/topiccontent-a2-pm2-v4.6.0-t%@-o0-p1-s20-c1-nt0-fs0-sp0-al0-cw360.json", str1];
        str = [NSString stringWithFormat:@"http://cont.app.autohome.com.cn/autov4.6/content/news/newscontent-n%@-t1.json", str1];
        self.pushWebblock(str, 0);
    }else if(num_page == 1){
        //点击快报页面
        str = [NSString stringWithFormat:@"http://cont.app.autohome.com.cn/autov4.6/content/News/fastnewscontent-n%@-lastid0.json", str1];
        if (self.delegate && [self.delegate respondsToSelector:@selector(pushPage:)]) {
            [self.delegate pushPage:str];
        }
    }else{
        str = [NSString stringWithFormat:@"http://cont.app.autohome.com.cn/autov4.6/content/news/newscontent-n%@-t0.json", str1];
        self.pushWebblock(str, 0);
    }
    
}


@end
